package net.huashitong.Indicators.utils;

import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Indicators.entity.UserInfo;
import net.huashitong.Indicators.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import sun.misc.BASE64Encoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class  TokenUtil {

    /**
     * 生成Token
     * Token：Nv6RRuGEVvmGjB+jimI/gw==
     * @return
     */
    public static String makeToken(){  //checkException
        //  7346734837483  834u938493493849384  43434384
        String token = (System.currentTimeMillis() + new Random().nextInt(999999999)) + "";
        //数据指纹   128位长   16个字节  md5
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            byte md5[] =  md.digest(token.getBytes());
            //base64编码--任意二进制编码明文字符   adfsdfsdfsf
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(md5);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    //false表示Token过期，true表示未过期
    public static boolean validateToken(UserInfo userInfo){
        //校验过期
        //获取当前时间
        String currentTime = new DateForIndUtils().getCurDate("yyyyMMdd HH:mm:ss");
        long currentTimeLong = new DateForIndUtils().fromDateStringToLong(currentTime);
        //比较时间是否大于两天
        if(StringUtils.isNotBlank(userInfo.getLocalTokenTime())){
            long localTokenTimeLong = new DateForIndUtils().fromDateStringToLong(userInfo.getLocalTokenTime());
            long timeSpan = currentTimeLong - localTokenTimeLong;
            long twoDays = 24*60*60*1000;
            //如果时间差大于两天，则本地Token过期
            if(timeSpan > twoDays){
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }
    }
}
